package edu.whu.assignment2;

import edu.whu.io.PropertiesLoader;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

public class Init {
    public static void initObject(String path){
        Properties props=findPropeties(path);
        Object o;
        try {
            o=createInstence(props);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        callInit(props,o);
    }
    public static Properties findPropeties(String path){
        Properties props=new Properties();
        try(InputStream input= PropertiesLoader.class.getResourceAsStream(path)){
            if(input==null){
                return null;
            }
            props.load(input);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return props;
    }

    public static Object createInstence(Properties props) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Object o=null;
        Class<?> bootstrapclass = Class.forName(props.getProperty("bootstrapClass"));
        o=bootstrapclass.newInstance();
        return o;
    }
    public static void callInit(Properties props,Object o) {
        try {
            Class<?> bootstrapclass = Class.forName(props.getProperty("bootstrapClass"));
            for(Method method:bootstrapclass.getDeclaredMethods()){
                if(method.isAnnotationPresent(InitMethod.class)){
                    method.invoke(o);
                }else{
                    System.out.println(method.getName()+" doesn't have @InitMethod");
                }
            }
        } catch (ClassNotFoundException | InvocationTargetException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
